package com.csscaps.auth.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.csscaps.auth.dao.SysOrgDao;
import com.csscaps.auth.model.SysOrg;
import com.csscaps.auth.model.SysUser;
import com.csscaps.auth.service.SysUserService;
import com.csscaps.system.base.BaseTreeNode;
import com.csscaps.system.shiro.ShiroUser;
import com.csscaps.system.utils.Constants;
import com.csscaps.system.utils.DateUtils;
import com.csscaps.system.utils.ResultUtil;
import com.csscaps.system.utils.UUIDGenerator;
import com.github.pagehelper.PageInfo;

@Controller
@RequestMapping(value = "/SysUser")
public class SysUserController {

	private final Log log = LogFactory.getLog(SysUserController.class);

	@Autowired
	private SysUserService sysUserService;

	@Autowired
	private SysOrgDao sysOrgDao;
	
	/**
	 * 新增
	 */
	@RequestMapping(value = "add", method=RequestMethod.POST)
	@ResponseBody
	public Map add(@Valid @RequestBody SysUser sysUser) {
		Map resoultMap = null;
		try {
			if (sysUserService.selectByUserAcount(sysUser.getUserAccount()) == null) {
				// 为用户信息添加密码转化，uuid，创建人等信息
				String base64Encoded = Base64.encodeToString(sysUser.getUserPassword().getBytes());
				sysUser.setUserPassword(base64Encoded);
				sysUser.setUserUuid(UUIDGenerator.genUuidStr());
				sysUser.setUserCreateTime(DateUtils.getCurrTime());
				sysUser.setDeleteStatus(Constants.NOT_DELETED);
				sysUser.setUserEnable(Constants.ENABLED);
				Subject subject = SecurityUtils.getSubject();
				String userName = String.valueOf(((ShiroUser) subject.getPrincipal()).getUserAccount());
				sysUser.setUserCreateUser(userName);
				sysUserService.insertByVo(sysUser);
				resoultMap = ResultUtil.getSuccessResult();
			} else {
				resoultMap = ResultUtil.getErrorResult("用户名已经存在！");
			}
		} catch (Exception e) {
			log.error("新增用户失败！"+e.toString());
			resoultMap = ResultUtil.getErrorResult();
		}
		return resoultMap;
	}

	/**
	 * 修改
	 * 
	 * @return
	 */
	@RequestMapping(value = "edit", method=RequestMethod.POST)
	@ResponseBody
	public Map edit(@Valid @RequestBody SysUser vo) {

		Map resoultMap = null;
		try {
			String base64Encoded = Base64.encodeToString(vo.getUserPassword().getBytes());
			vo.setUserPassword(base64Encoded);
			vo.setUserUpdateTime(new Date());
			sysUserService.updateByVO(vo);
			resoultMap = ResultUtil.getSuccessResult();
		} catch (Exception e) {
			e.printStackTrace();
			resoultMap = ResultUtil.getErrorResult();
		}

		return resoultMap;
	}

	/**
	 * 修改
	 * 
	 * @return
	 */
	@RequestMapping(value = "editPwd", method=RequestMethod.POST)
	@ResponseBody
	public Map editPwd(@Valid @RequestBody SysUser vo) {

		Map resoultMap = null;
		try {
			SysUser	userInfo = sysUserService.selectByUserAcount(vo.getUserAccount());
			String base64Encoded = Base64.encodeToString(vo.getUserPassword().getBytes());
			userInfo.setUserPassword(base64Encoded);
			userInfo.setUserUpdateTime(new Date());
			sysUserService.updateByVO(userInfo);
			resoultMap = ResultUtil.getSuccessResult();
		} catch (Exception e) {
			e.printStackTrace();
			resoultMap = ResultUtil.getErrorResult();
		}

		return resoultMap;
	}

	/**
	 * 删除
	 * 
	 * @return
	 */
	@RequestMapping(value = "remove/{userIds}", method=RequestMethod.GET)
	@ResponseBody
	public Map remove(@PathVariable("userIds") String userIds) {

		Map resoultMap = null;
		try {
			// 删除用户信息
			String[] userIdArr = userIds.split(",");
			sysUserService.deleteUser(userIdArr);
			resoultMap = ResultUtil.getSuccessResult();
		} catch (Exception e) {
			e.printStackTrace();
			resoultMap = ResultUtil.getErrorResult();
		}
		return resoultMap;
	}

	/**
	 * 验证用户旧密码是否正确
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "validateUserPassword")
	@ResponseBody
	public Map validateUserPassword(@Valid @RequestBody SysUser user) {
		Map resoultMap = null;
		// 验证用户密码
		Subject subject = SecurityUtils.getSubject();
		String userName = String.valueOf(((ShiroUser)subject.getPrincipal()).getUserAccount());
		SysUser	userInfo = sysUserService.selectByUserAcount(userName);
		
		String pwd = null;
		if (userInfo != null) {
			pwd = Base64.decodeToString(userInfo.getUserPassword());
		}
		if (pwd.equals(user.getUserPassword())) {
			resoultMap = ResultUtil.getSuccessResult("旧密码输入正确！");
		}
		if (!pwd.equals(user.getUserPassword())) {
			resoultMap = ResultUtil.getErrorResult("旧密码输入有误！");
		}
		return resoultMap;
	}

	/**
	 * 查询
	 * 
	 * @return
	 */
	@RequestMapping(value = "getAll", method=RequestMethod.GET)
	@ResponseBody
	public Map getAll() {

		Map resoultMap = null;
		try {
			List<SysUser> list = sysUserService.selectAll();
			resoultMap = ResultUtil.getSuccessResult(list);
		} catch (Exception e) {
			e.printStackTrace();
			resoultMap = ResultUtil.getErrorResult();
		}

		return resoultMap;
	}

	/**
	 * 根据条件查询
	 * 
	 * @return
	 */
	@RequestMapping(value = "get", method=RequestMethod.POST)
	@ResponseBody
	public Map get(@Valid @RequestBody SysUser vo) {

		Map resoultMap = null;
		try {
			List<SysUser> list = sysUserService.selectByVo(vo);
			resoultMap = ResultUtil.getSuccessResult(list);
		} catch (Exception e) {
			e.printStackTrace();
			resoultMap = ResultUtil.getErrorResult();
		}

		return resoultMap;
	}

	/**
	 * 分页查询
	 * 
	 * @return
	 */
	@RequestMapping(value = "getPage", method=RequestMethod.POST)
	@ResponseBody
	public Map getPage(@Valid @RequestBody SysUser vo) {

		Map resoultMap = null;
		try {
			PageInfo<SysUser> pageInfo = sysUserService.selectPage(vo);
			// 机构名称处理
			for (int i = 0; i < pageInfo.getList().size(); i++) {
				SysOrg org = sysOrgDao.selectByPk(pageInfo.getList().get(i)
						.getUserOrgUuid());
				if(org != null) {
					pageInfo.getList().get(i).setUserOrgName(org.getOrgName());
				}
			}
			resoultMap = ResultUtil.getSuccessResult(pageInfo);
		} catch (Exception e) {
			e.printStackTrace();
			resoultMap = ResultUtil.getErrorResult();
		}

		return resoultMap;
	}

	/**
	 * 查询用户以及由用户创建的子机构
	 * 
	 * @return
	 */
	@RequestMapping(value = "getSubUser/{userAccount}", method=RequestMethod.GET)
	@ResponseBody
	public Map getSubUser(@PathVariable("userAccount") String userAccount) {
		Map resoultMap = null;
		try {
			List<SysUser> userList = sysUserService.selectSubUser(userAccount);
			resoultMap = ResultUtil.getSuccessResult(userList);
		} catch (Exception e) {
			e.printStackTrace();
			resoultMap = ResultUtil.getErrorResult();
		}
		return resoultMap;
	}

	/**
	 * 用户角色授权 ，支持多对多关系 parameter :{checkUserList:[...],checkedRoleIds:[...]}
	 * 
	 * @return
	 */
	@RequestMapping(value = "authorize", method=RequestMethod.POST)
	@ResponseBody
	public Map authorize(@RequestBody String parameter) {
		Map resoultMap = null;
		try {
			sysUserService.authorize(parameter);
			resoultMap = ResultUtil.getSuccessResult();
		} catch (Exception e) {
			e.printStackTrace();
			resoultMap = ResultUtil.getErrorResult();
		}
		return resoultMap;
	}

	@RequestMapping(value = "getUserOrgTree")
	@ResponseBody
	public Map<String, Object> getUserOrgTree(String userId) {
		Map resoultMap = null;
		try {
			List<BaseTreeNode> list = sysUserService.getUserOrgTree(userId);
			resoultMap = ResultUtil.getSuccessResult(list);
		} catch (Exception e) {
			e.printStackTrace();
			resoultMap = ResultUtil.getErrorResult();
		}
		return resoultMap;
	}
	/**
	 * 用户审核
	 */
/*	@SuppressWarnings("unchecked")
	@RequestMapping(value = "userApprove", method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> userApprove(@RequestBody Map<String, Object> paraMap) {

		Map<String, Object> resoultMap = null;
		try {
			sysUserService.userApprove(paraMap);
			resoultMap = ResultUtil.getSuccessResult();
		} catch (Exception e) {
			log.error("用户:" + String.valueOf(paraMap.get("userAccount")) + "，审核失败！" + e.toString());
			resoultMap = ResultUtil.getErrorResult();
		}
		return resoultMap;
	}
	*/
	 
	
}
